<template>
  <div v-loading="loading">
    <!-- 添加导出按钮 -->
    <div class="flex mb-4">
      <el-button
        type="primary"
        @click="exportRecipeExcel(displayedWeekDays, tableData, currentWeeklyMenu)"
        >导出采购单</el-button
      >
    </div>

    <el-table :data="tableData" border class="weekly-table">
      <el-table-column prop="title" label="" :width="getViewportPx(90)" fixed />
      <el-table-column
        v-for="(day, index) in displayedWeekDays"
        :key="index"
        :prop="'day' + day.value"
        :label="day.date ? `${day.label}(${day.date})` : day.label"
        :min-width="180"
        :width="getViewportPx(220)"
        class-name="!vertical-top"
      >
        <template #default="scope">
          <div class="recipe-cell p-4px rounded h-full">
            <div v-if="scope.row.type === 'people'">
              <el-input-number
                v-model="scope.row[`day${day.value}`]"
                :min="0"
                controls-position="right"
                class="!w-full"
                @change="(value) => handlePeopleChange(value, day.value)"
              />
            </div>
            <div v-else-if="scope.row.type === 'deliveryTime'">
              <el-date-picker
                v-model="scope.row[`day${day.value}`]"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm"
                placeholder="选择日期时间"
                class="!w-full"
              />
            </div>
            <div v-else-if="scope.row.type === 'ingredients'">
              <div
                v-for="(item, itemIndex) in scope.row[`day${day.value}`]"
                :key="itemIndex"
                class="ingredient-item flex justify-between mb-2px"
              >
                <span class="ingredient-name text-14px">{{ item.foodName }}</span>
                <span class="food-usage text-12px text-gray-500 flex-shrink-0"
                  >{{ formatWeight(item.usage) }}斤</span
                >
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { useMessage } from '@/hooks/web/useMessage'
import { formatDate } from '@/utils/formatTime'
import { getWeekStartDate, formatMonthDay } from '../utils/dateUtils'
import { RecipeMenusDailyApi } from '@/api/school/recipe/menusDaily'
import { getViewportPx } from '@/utils/formatter'
import { useExportRecipeExcel } from '../utils/useExportRecipeExcel'
// 定义组件属性
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  currentWeeklyMenu: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件
const emit = defineEmits(['update:loading'])

const message = useMessage()
const { formatWeight, exportRecipeExcel } = useExportRecipeExcel()
// 采购数据
const shoppingData = ref<any[]>([])

// 所有星期选项
const allWeekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

// 实际需要展示的星期选项（根据 shoppingData 中的数据）
const displayedWeekDays = computed(() => {
  // 创建一个映射，将weekDay值映射到日期
  const dateMap: Record<string, string> = {}

  // 从shoppingData中获取日期信息
  if (shoppingData.value && shoppingData.value.length > 0) {
    shoppingData.value.forEach((item: any) => {
      if (item.weekDay) {
        const dayIndex = parseInt(item.weekDay)
        if (item.menuDate) {
          dateMap[dayIndex] = formatDate(new Date(item.menuDate), 'MM.DD')
        }
      }
    })
  }

  // 如果shoppingData中没有足够的数据，从currentWeeklyMenu中计算日期
  if (
    props.currentWeeklyMenu &&
    props.currentWeeklyMenu.weekYear &&
    props.currentWeeklyMenu.weekNumber
  ) {
    // 计算这一周的每一天日期
    const startDate = getWeekStartDate(
      props.currentWeeklyMenu.weekYear,
      props.currentWeeklyMenu.weekNumber
    )

    allWeekDays.forEach((day) => {
      // 如果dateMap中还没有这个日期，则计算并添加
      if (!dateMap[day.value]) {
        const currentDate = new Date(startDate)
        currentDate.setDate(startDate.getDate() + day.value - 1) // 周一为第一天
        dateMap[day.value] = formatMonthDay(currentDate)
      }
    })
  }

  // 只返回 shoppingData 中实际存在的日期
  const result: { label: string; value: number; date: string }[] = shoppingData.value
    .map((item: any) => {
      const dayIndex = parseInt(item.weekDay)
      const day = allWeekDays.find((d) => d.value === dayIndex)
      return day
        ? {
            ...day,
            date: dateMap[day.value] || ''
          }
        : null
    })
    .filter((item): item is { label: string; value: number; date: string } => item !== null) // 过滤掉 null 值并确保类型安全

  // 按照星期顺序排序
  return result.sort((a, b) => a.value - b.value)
})

// 获取当天10点的时间
const getDefaultDeliveryTime = (menuDate: string | number) => {
  if (!menuDate) return null

  const date = new Date(menuDate)
  date.setHours(10, 0, 0, 0) // 设置为当天10点
  return formatDate(date, 'YYYY-MM-DD HH:mm:ss')
}

// 表格数据
const tableData = computed(() => {
  // 表格行数据
  const rows = [
    { title: '用餐人数', type: 'people' },
    { title: '配送时间', type: 'deliveryTime' },
    { title: '食材清单', type: 'ingredients' }
  ]

  // 为每一行填充每天的数据
  rows.forEach((row) => {
    displayedWeekDays.value.forEach((day) => {
      const dayData = shoppingData.value.find((item) => parseInt(item.weekDay) === day.value)

      if (row.type === 'people') {
        // 人数数据
        row[`day${day.value}`] = dayData?.studentCount || 0
      } else if (row.type === 'deliveryTime') {
        // 配送时间数据
        if (dayData?.deliveryTime) {
          // 如果已有配送时间数据，则使用该数据
          row[`day${day.value}`] = dayData.deliveryTime
        } else if (dayData?.menuDate) {
          // 如果没有配送时间但有菜单日期，则设置默认时间为当天10点
          row[`day${day.value}`] = getDefaultDeliveryTime(dayData.menuDate)
        } else {
          // 如果都没有，则设为null
          row[`day${day.value}`] = null
        }
      } else if (row.type === 'ingredients') {
        // 食材清单数据
        row[`day${day.value}`] = dayData?.totalUsagesList || []
      }
    })
  })

  return rows
})

// 处理人数变化
const handlePeopleChange = async (value: number | undefined, dayIndex: number) => {
  // 当人数变化时，调用API更新当天的数据
  if (props.currentWeeklyMenu?.menuId && value !== undefined) {
    emit('update:loading', true)
    try {
      const res = await RecipeMenusDailyApi.getRecipeMenusDailyShoppingDay({
        menuId: props.currentWeeklyMenu.menuId,
        weekDay: dayIndex.toString(),
        studentCount: value
      })

      // 更新对应天的数据
      const dayDataIndex = shoppingData.value.findIndex(
        (item) => parseInt(item.weekDay) === dayIndex
      )
      if (dayDataIndex !== -1) {
        shoppingData.value[dayDataIndex] = res
      } else {
        shoppingData.value.push(res)
      }
    } catch (err) {
      message.error('更新食材采购清单失败')
    } finally {
      emit('update:loading', false)
    }
  }
}

// 加载采购清单数据
const loadShoppingData = async (menuId: number) => {
  emit('update:loading', true)
  try {
    // 使用正确的API方法 getRecipeMenusDailyShopping
    const res = await RecipeMenusDailyApi.getRecipeMenusDailyShopping(menuId)
    shoppingData.value = res || []
  } catch (err) {
    message.error('加载食材采购清单失败')
  } finally {
    emit('update:loading', false)
  }
}

// 监听currentWeeklyMenu变化，当menuId改变时重新加载数据
watch(
  () => props.currentWeeklyMenu?.menuId,
  async (newMenuId, oldMenuId) => {
    if (newMenuId && newMenuId !== oldMenuId) {
      await loadShoppingData(newMenuId)
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  loadShoppingData
})
</script>

<style lang="scss" scoped>
.weekly-table {
  width: fit-content;

  :deep(.el-table__cell) {
    padding: 8px 0;
  }

  .recipe-cell {
    height: 100%;
  }

  .ingredient-item {
    display: flex;
    justify-content: space-between;
  }
}
</style>
